<?php
class Application_Model_Order extends Application_Model_DomainObject implements Application_Model_PayInterface {
		
	/**
	 * 待付款
	 * @var unknown_type
	 */
	const STATUS_PAYING=0;
    
    /**
     * 已付款 
     */
    const STATUS_PAID=1;


    /**
	 * 待确认
	 * @var unknown_type
	 */
	const STATUS_CONFRIM=2;
	

    /**
	 * 卖家已发货
	 */
	const STATUS_SELLER_SENDED=4;
    
    /**
     * 已入库 
     */
    const STATUS_INSTORE=5;


    /**
	 * 已完成
	 * @var unknown_type
	 */
	const STATUS_COMPLATED = 99;
	
	/**
	 * 等待卖家发货
	 * @var unknown_type
	 */
	const STATUS_UNSEND=3;
    
    /**
     * 取消状态 
     */
    const STATUS_CANCEL=10;

    /**
     * 退货 
     */
    const STATUS_BANK=11;
    
    /**
     *  部分退货
     */
    const STATUS_PartBank=12;

    
	protected $_id;
    
    /**
     * 订单号
     */
    protected $_orderNo;

    //确认时间
    protected $_dateConfrim;
	
    //创建时间
	protected $_dateCreated;
	
    //入库时间
	protected $_dateInStore;
	
    //产品费用
	protected $_productTotal;
	
    //邮费
	protected $_shipFee;
	
    //状态
	protected $_status;
	
    //父订单
	protected $_parentId;
	
    //订单总额
	protected $_sum;
	
    //备注
	protected $_comment;
	
    //用户ID
	protected $_userId;
	
	//所有的商品
	private $_items;
        
    //店铺ID
    protected $_shopId;
    
    //采购单号,指在第三方网站上的订单号
    protected $_procureNo;
    
    //物流公司
    protected $_logistics;

    //物流单号
    protected $_logisticsNo;

    //采购日期
    protected $_dateProcure;

    protected $_problemContent;//问题原因
    
    protected $_ckPass;
    private $_logisticsBy;
    
    public function getLogisticsBy(){
        if($this->_logisticsBy == null){
            $this->_logisticsBy = Application_Model_shipType::load($this->_logistics);
            if($this->_logisticsBy==NULL)
                $this->_logisticsBy = new Application_Model_shipType();
        }
        return $this->_logisticsBy;
    }

    
    /**
	 * 返回订单中的商品
	 * @return array
	 */
	public function getItems(){
		if(NULL!= $this->_items)
			return $this->_items;
		
		if(isset($this->_id))
			$this->_items = Application_Model_OrderItem::getByOrderId($this->_id);
		else
			$this->_items = array();
		
		return $this->_items;		
	}
	
	/**
	 * 添加一个产品到订单中
	 * @param Application_Model_OrderItem $orderItem
	 */
	public function addItem(Application_Model_OrderItem $orderItem){
		$this->getItems();
		
		array_push($this->_items, $orderItem);
	}
    
    private $_user;
    public function getUser(){
        if($this->_user==NULL)
            $this->_user=  Application_Model_User::load ($this->_userId);
        return $this->_user;
    }

        /**
	 * 从购物车生成一个订单
	 * @param Application_Model_Cart $cart 购物车
	 * @return Application_Model_Order
	 */
	public static function fromCart(Application_Model_Cart $cart){
		$order = new Application_Model_Order();
		$order->DateCreated = date('Y-m-d H:i:s');
		$order->Status = Application_Model_Order::STATUS_PAYING;
		$order->UserId = Application_Model_User::current()->Id;		
		$productTotal = $cart->ProductTotal;
		$shipFee = $cart->ShipFeeTotal;		
		foreach ($cart->getItems() as $item){			
			$orderItem = new Application_Model_OrderItem();
			$orderItem->ProductId = $item->ProductId;
			$orderItem->Price = $item->Price;
			$orderItem->Quantity = $item->Quantity;
			$orderItem->ProductName = $item->ProductName;
			$orderItem->Comment = $item->Comment;
			$order->addItem($orderItem);
			//$productTotal += $item->Price;
			//$shipFee += $item->ShipFee;
		}
		$order->Sum = $productTotal + $shipFee;
		return $order;
	}
    
    public function getStatusText(){
        $statusText = array('0'=>'待付款',1=>'已付款，等待下单','2'=>'已受理','3'=>'等待卖家发货',4=>'卖家已发货'
            ,5=>'已入库',10=>'已取消',11=>'已退款',12=>'部分退款',''=>'未知状态');
        return $statusText[$this->_status];;
    }
    

    /**
	 * 保存订单，并关联的把订单项也保存起来
	 * 
	 */
	public function save(){		
		parent::save();
		foreach ($this->getItems() as $item){
			$item->OrderId = $this->Id;
			$item->save();
		}
	}
    
    protected static function getDb(){
        return new Application_Model_DbTable_Order();
    }

    /**
     * 返回用户的订单列表
     * @param 用户ID $userId
     * @param 开始时间 $startTime
     * @param 结束时间 $endTime
     * @param 开始序号 $start
     * @param int $pageSize 一次返回数量
     * @return type 
     */
    public static function getByUser($userId,$startTime,$endTime,$start,$pageSize){
        return Application_Model_Order::getDb()->getByUser($userId,$startTime,$endTime,$start,$pageSize);
    }
    
    /**
     * 根据指定的条件返回订单
     * @param int $orderId
     * @param int $memberId
     * @param date $startTime 开始时间
     * @param date $endTime 结束时间
     * @param int $status 订单状态
     * @param int $count
     * @param int $offset
     * @return 返回格式为 array('size'=>?,'list'=>?,'pages'=>?,'index'=>?) 
     * size为查询记录的总条数，list为返回的array型数据，pages是指有多少页，index为当前是哪一页 
     */
    public static function getByFilter($orderId,$memberId,$startTime,$endTime, $status,$keyword, $count, $offset){
        $where = array();
        $and = '';
        if($orderId != NULL){
            $where['Id = '] = $orderId;
            $and = ' and ';
        }
        
        if ($memberId != NULL){
            $where[$and.' userId = '] = $memberId;
            $and = ' and ';
        }
        
        if($startTime != NULL){
            $where[$and.' dateCreated >= '] = $startTime;
            $and = ' and ';
        }
        
        if($endTime != NULL){
            $where[$and.' dateCreated <= '] = $endTime;
            $and = ' and ';
        }
        
        if ($status != NULL && $status!=''){
            $where[$and.' status = '] = $status;
            $and = ' and ';
        }
        
        if ($keyword != NULL){
            
        }
        
        return Application_Model_Order::getDb()->queryPage($where, 'dateCreated desc', $count, $offset);
        
    }
    
    public static function getUncomplate($userId){
    	//return Application_Model_Order::getDb()->getUncomplate($userId);
            $order=new Application_Model_DbTable_Order();
            
    }
    
    public static function getCountByStatus($userId,$status){
    	return Application_Model_Order::getDb()->count(array('userId'=>$userId,'status'=>$status));
    }
    
    public static function getByNo($orderNo){
        return Application_Model_Order::getDb()->queryOne(array('orderNo'=>$orderNo));
    }


    public function getMoney(){
        return $this->Sum;
    }
    
    public function getPayName() {
        return '代购';
    }
    
    private $_shop;
    public function getShop(){
        if($this->_shop==NULL)
            $this->_shop=new Application_Model_Shop($this->_shopId);
        return $this->_shop;
    }
    
    public function setPaid(){
        $this->Status = Application_Model_Order::STATUS_PAID;
    }
    
    public function getBillNo() {
        return $this->getOrderNum();
    }
    
    /**
     * 返回订单号
     * @return type 
     */
    public function getOrderNum(){
        return 'U2013'.$this->Id.substr($this->DateCreated,17,1);
    }

    public function getPayDescription() {
        return '代购订单';
    }
    
    public function canPay($userId) {
        if($this->_status != Application_Model_Order::STATUS_PAYING)
            return FALSE;
        if($this->_userId != $userId)
            return FALSE;
        return TRUE;
    }
    
    /**
     * 根据几个ID，创建一个空订单，供支付使用
     */
    public static function createByOrderIds($ids){
        return Application_Model_OrderParent::createByOrderIds($ids);
    }
    
    /**
     * 获取该状态下的订单的数量
     * @param type $date 时间
     * @param type $status 状态
     */    
    public static function countorder($date,$status)
    {
        $and = '';
        $where = array();

        if ($date != '') {
            $where[' dateCreated > '] = date('Y-m-d');
            $and = 'and ';
        }
        if ($status != '') {
            $where[$and . ' status = '] = $status;
        }
        return Application_Model_Order::getDao()->count($where);
    }
    public static function getOrdercount($dateinbegin,$dateinend)
    {
        $where = "";
        $and = "";
        if($dateinbegin != "" && $dateinend == ""){
            $where[" status != "] = Application_Model_Order::STATUS_PAYING;
            $and = " and ";
            $where[$and . " (status != "] = Application_Model_Order::STATUS_CANCEL;
            $where[")".$and." status != "] = Application_Model_Order::STATUS_BANK;
            $where[$and." dateCreated > "] = $dateinbegin." 00:00:00";
            $and = " and ";
            $where[$and." dateCreated < "] = $dateinbegin." 23:59:59";
            $result = Application_Model_Order::getDb()->queryAll($where);
            $i = strtotime($dateinbegin);
            $arrre[$i]["num"] = count($result);
            $arrre[$i]["ysje"] = 0;
            $arrre[$i]["zyf"] = 0;
            $arrre[$i]["bfyk"] = 0;
            if ($result) {
                foreach ($result as $value) {
                    $arrre[$i]["ysje"] = $arrre[$i]["ysje"] + $value->sum;
                    $arrre[$i]["zyf"] = $arrre[$i]["zyf"] + $value->shipFee;
                    if ($value->status == Application_Model_Order::STATUS_PartBank) {
                        $bftkItem = Application_Model_OrderItem::getByOrderId($value->id);
                        if ($bftkItem) {
                            foreach ($bftkItem as $key => $itemvalue) {
                                if ($itemvalue->status == 1) {
                                    $arrre[$i]["bfyk"] = $arrre[$i]["bfyk"] + ($itemvalue->quantity * $itemvalue->price);
                                }
                            }
                        }
                    }
                }
            }
        }
        if($dateinend != "" && $dateinbegin == ""){
            $where[" status != "] = Application_Model_Order::STATUS_PAYING;
            $and = " and ";
            $where[$and . " (status != "] = Application_Model_Order::STATUS_CANCEL;
            $where[")".$and." status != "] = Application_Model_Order::STATUS_BANK;
            $where[$and." dateCreated > "] = $dateinend." 00:00:00";
            $and = " and ";
            $where[$and." dateCreated < "] = $dateinend." 23:59:59";
            $result = Application_Model_Order::getDb()->queryAll($where);
            $i = strtotime($dateinend);
            $arrre[$i]["num"] = count($result);
            $arrre[$i]["ysje"] = 0;
            $arrre[$i]["zyf"] = 0;
            $arrre[$i]["bfyk"] = 0;
            if ($result) {
                foreach ($result as $value) {
                    $arrre[$i]["ysje"] = $arrre[$i]["ysje"] + $value->sum;
                    $arrre[$i]["zyf"] = $arrre[$i]["zyf"] + $value->shipFee;
                    if ($value->status == Application_Model_Order::STATUS_PartBank) {
                        $bftkItem = Application_Model_OrderItem::getByOrderId($value->id);
                        if ($bftkItem) {
                            foreach ($bftkItem as $key => $itemvalue) {
                                if ($itemvalue->status == 1) {
                                    $arrre[$i]["bfyk"] = $arrre[$i]["bfyk"] + ($itemvalue->quantity * $itemvalue->price);
                                }
                            }
                        }
                    }
                }
            }
        }
        if($dateinend != "" && $dateinbegin != ""){
            $sdate = $dateinbegin<=$dateinend?$dateinbegin:$dateinend;
            $edate = $dateinbegin>=$dateinend?$dateinbegin:$dateinend;
            $stime=strtotime($sdate);
            $etime=strtotime($edate);
            for($i=$stime;$i<=$etime;$i++){
                $where = "";
                $and = "";
                $where[" status != "] = Application_Model_Order::STATUS_PAYING;
                $and = " and ";
                $where[$and." (status != "] = Application_Model_Order::STATUS_CANCEL;
                $where[")".$and." status != "] = Application_Model_Order::STATUS_BANK;
                $where[$and . " dateCreated > "] = date("Y-m-d H:i:s", $i);
                $where[$and . " dateCreated < "] = date("Y-m-d H:i:s", ($i+86400));
                $result = Application_Model_Order::getDb()->queryAll($where);
                $arrre[$i]["num"] = count($result);
                $arrre[$i]["ysje"] = 0;
                $arrre[$i]["zyf"] = 0;
                $arrre[$i]["bfyk"] = 0;
                if ($result) {
                    foreach ($result as $value) {
                        $arrre[$i]["ysje"] = $arrre[$i]["ysje"] + $value->sum;
                        $arrre[$i]["zyf"] = $arrre[$i]["zyf"] + $value->shipFee;
                        if($value->status == Application_Model_Order::STATUS_PartBank){
                            $bftkItem = Application_Model_OrderItem::getByOrderId($value->id);
                            if($bftkItem){
                                foreach ($bftkItem as $key => $itemvalue) {
                                    if($itemvalue->status == 1){
                                        $arrre[$i]["bfyk"] = $arrre[$i]["bfyk"] + ($itemvalue->quantity * $itemvalue->price);
                                    }
                                }
                            }
                        }
                    }
                }
                $i+= 86399;	
            }
        }
        if($dateinend == "" && $dateinbegin == ""){
            $arrre = array();
            $nowYm = date("Y-m");
            $nowd = date("d");
            for ($i = 1; $i <= $nowd; $i++) {
                $where = "";
                $and = "";
                $where[" status != "] = Application_Model_Order::STATUS_PAYING;
                $and = " and ";
                $where[$and." (status != "] = Application_Model_Order::STATUS_CANCEL;
                $where[")".$and." status != "] = Application_Model_Order::STATUS_BANK;
                $where[$and . " dateCreated > "] = $nowYm . "-" . $i;
                $where[$and . " dateCreated < "] = $nowYm . "-" . ($i + 1);
                $result = Application_Model_Order::getDb()->queryAll($where);
                $j = strtotime($nowYm."-".$i);
                $arrre[$j]["num"] = count($result);
                $arrre[$j]["ysje"] = 0;
                $arrre[$j]["zyf"] = 0;
                $arrre[$j]["bfyk"] = 0;
                if ($result) {
                    foreach ($result as $value) {
                        $arrre[$j]["ysje"] = $arrre[$j]["ysje"] + $value->sum;
                        $arrre[$j]["zyf"] = $arrre[$j]["zyf"] + $value->shipFee;
                        if($value->status == Application_Model_Order::STATUS_PartBank){
                            $bftkItem = Application_Model_OrderItem::getByOrderId($value->id);
                            if($bftkItem){
                                foreach ($bftkItem as $key => $itemvalue) {
                                    if($itemvalue->status == 1){
                                        $arrre[$j]["bfyk"] = $arrre[$j]["bfyk"] + ($itemvalue->quantity * $itemvalue->price);
                                    }
                                }
                            }
                        }
                    }
                }
                
            }
        }
//        var_dump($arrre);exit;
        return $arrre;
    }
    public static function bylogistics($logisticsNo) {
        $where[' logisticsNo = '] = $logisticsNo;
        return Application_Model_Order::getDao()->queryOne($where);
    }
    /**
     * 根据物流单号，获取包裹信息
     * @param string $shipNo
     * @return type
     */
    public static function getByShipNo($shipNo) {
        return Application_Model_Order::getDao()->queryOne(array('logisticsNo' => $shipNo));
    }
    /**
     * 获取商品信息
     * @return type
     */
    public function getshipdetail() {
        return Application_Model_OrderItem::getByOrderId($this->_id);
    }
    public function getlogname() {
        if ($this->_logistics) {
            return Application_Model_shipType::load($this->_logistics);
        }
    }
     public static function getStatusList() {
        $statusText = array('0' => '待付款', '1' => '已付款，等待下单', '2' => '已受理', '3' => '等待卖家发货', '4' => '卖家已发货'
            , '5' => '已入库', '10' => '已取消', '11' => '已退款', '12' => '部分退款', '' => '未知状态');
        return $statusText;
    }
    /**
     * 获取客户信息
     * @return type
     */
    public function getbyuserdetail() {
        return Application_Model_User::getByUserId($this->_userId);
    }
     public static function getStatusDescription($status) {
        $statusText = Application_Model_Order::getStatusList();
        $statusStr = $statusText[$status];
        return $statusStr;
    }
     /**
     * 根据userid，加载user对象
     * @author wuzw
     * @return type
     */
    public function getuserinfo() {
        if ($this->_userId) {
            return Application_Model_User::load($this->_userId);
        }
    }
    /**
     * 获取分页的数据
     * @param type $username  名字
     * @param type $orderno   订单号
     * @param type $starttime  开始时间
     * @param type $endtime  结束时间
     * @param type $status   状态
     * @param type $pagesize  每页显示条数
     * @param type $pageindex  从第几条数据开始显示
     * @return type
     */
//    public static function getByPages($userid, $username, $storeno, $productName, $orderno, $starttime, $endtime, $status, $procureNo, $logisticsNo, $pagesize, $pageindex) 
    public static function getByPages($quick, $starttime, $endtime, $status, $pagesize, $pageindex,$userid = null) //快速搜索
    {
        //王良峰 -- 快速搜索
        $where = array();
        $and = "";
        $uwhere = "";
        $uand = "";
        if($quick != ""){
            $and = "(";
            $uwhere[$uand.' id = '] = $quick;
            $uand = " or ";
            $uwhere[$uand.' nikename like '] = "%".$quick."%";
            $uwhere[$uand.' storeno = '] = $quick;
            $userItem = Application_Model_User::getDao()->queryAll($uwhere);
            if($userItem != null){
                $inuserid = "(";
                foreach ($userItem as $userval) {
                    $inuserid.= $userval->id . ",";
                }
                $inuserid.= "0)";
                $where[$and." userId in "] = $inuserid;
                $and = " or ";
            }else{
                $where[$and." userId = "] = $quick;
                $and = " or ";
            }
            $pwhere[' productName like '] = "%".$quick."%";
            if(strstr($quick,"U") || strstr($quick,"u")){
                $orderno = substr($quick, 5, strlen($quick) - 6);
            }else{
                $orderno = $quick;
            }
            $pand = " or ";
            $pwhere[$pand.' orderId = '] = $orderno;
            $orItem = Application_Model_OrderItem::getDao()->queryAll($pwhere);
            if($orItem != null){
                $pid = "(";
                foreach ($orItem as $orval) {
                    $pid.= $orval->orderId . ',';
                }
                $pid.= "0)";
                $where[$and." id in "] = $pid;
                $and = " or ";
            }else{
                $where[$and." id = "] = $orderno;
                $and = " or ";
            }
            $where[$and." procureNo like "] = "%".$quick."%";
            $where[$and." logisticsNo like "] = "%".$quick."%";
            $where[" ) and "] = 1;
            $and = " and ";
           
        }
        if($starttime != "")
        {
            $where[$and . " dateCreated >= "] = $starttime;
            $and = " and ";
        }
        if ($endtime != "") {
            $where[$and . " dateCreated <= "] = $endtime;
            $and = " and ";
        }
        if ($status != "") {
            $where[$and . " status = "] = $status;
            $and = " and ";
        }
        if($userid != null){
            $where[$and." userId = "] = $userid;
            $and = " and ";
        }
//        var_dump($where);exit;
        return Application_Model_Order::getDao()->queryPage($where,"dateCreated desc",$pagesize,$pageindex);
        
    }
    public static function getstatusname($status){
        $statusText = Application_Model_Order::getStatusList();
        $statusStr = $statusText[$status];
        return $statusStr;
    }
    /**
     * 全部退款
     * @param order id $id
     * @param user id $userid
     * @return int
     */
    public static function retuenMoney($id, $userid) {
        $obj = Application_Model_Order::load($id);
        $arrup = array();
        if ($obj) {
            try {
                $db = Application_Model_OrderItem::getDao();
                $db->beginTran();

                //1、修改Order状态
                $obj->status = 11;      //状态11：全部退款
                $obj->save();
                $accountObj = Application_Model_UserAccount::load($userid);

                $itemList = $obj->getshipdetail();
                $itemmoney = 0;
                foreach ($itemList as $item) {
                    /* 如果已经退款的，则不处理 */
                    if ($item->status == 1)
                        continue;

                    //2、修改Item状态 
                    $orderItemObj = Application_Model_OrderItem::load($item->id);
                    $orderItemObj->status = 1;  //OderItem 状态改为1，退款
                    $orderItemObj->save();
                    $itemmoney = $itemmoney + ($orderItemObj->price * $orderItemObj->quantity);
                    $arrup[$orderItemObj->id] = $orderItemObj->price;
                }
                $shipFee = (int) ($obj->shipFee);
                if ($shipFee > 0) {
                    $itemmoney = $itemmoney + $shipFee;
                }
                $beforeMoney = $accountObj->money;
                //3、退还用户帐号
                $accountObj->money = $accountObj->money + $itemmoney;
                $accountObj->save();
                Application_Model_Operate::intooperate($itemmoney, Application_Model_Operate::Type_buyshoprefund, $obj->getOrderNum(), $userid);
                
                $dateCreated = date('Y-m-d H:i:s', time());
                $comment = "代购订单:" . $obj->getOrderNum() . '(包含运费)全部退款';
                $afterMoney = $beforeMoney + $itemmoney;
//
                $userAccountHistory = new Application_Model_UserAccountHistory();
                $userAccountHistory->type = 4;
                $userAccountHistory->beforeMoney = $beforeMoney;
                $userAccountHistory->afterMoney = $afterMoney;
                $userAccountHistory->comment = $comment;
                $userAccountHistory->dateCreated = $dateCreated;
                $userAccountHistory->relaseId = $obj->id;
                $userAccountHistory->accountId = $userid;
                $userAccountHistory->save();
                //检查是否有运费，如有，则把运费也退回去
                

                $db->commit();
            } catch (Exception $ex) {
                $db->rollBack();
                return 0;
            }

            return $arrup;
        } else {
            return 0;
        }
    }
     public static function getAllOrder()
    {
        $where[" (procureNo != "] = "";
        $where[" or procureNo != NULL ) and "] = 1;
        $where[" and (logisticsNo = "] = "";
        $where[" or logisticsNo is NULL ) and "] = 1;
        $where[' and status not in '] = "(".Application_Model_Order::STATUS_CANCEL.",".Application_Model_Order::STATUS_BANK.")";
        return Application_Model_Order::getDao()->queryAll($where);
    }
}

class Application_Model_OrderParent extends Application_Model_Order implements Application_Model_PayInterface{
    
    protected $_ids;
    
    protected $_orders;

    /**
     * 根据几个ID，创建一个空订单，供支付使用
     */
    public static function createByOrderIds($ids){
        $splitIds = split(',', $ids);
        $order = new Application_Model_OrderParent();
        $order->Ids = $splitIds; 
        $orders = array();
        foreach ($splitIds as $id){
            $item = Application_Model_Order::load($id);
            $orders[] = $item;
        }
        $order->_orders = $orders;
        return $order;
    }
    
    public function getBillNo() {
        return $this->_orders[0]->OrderNum;
    }
    
    public function setPaid() {
        foreach ($this->_orders as $order){
            $order->setPaid();
        }
    }
    
    public function getMoney() {
        $sum =0;
        foreach ($this->_orders as $order){
            $sum += $order->Sum;
        }
        return $sum;
    }
    
    public function getPayName() {
        return '代购订单';
    }
    
    public function getPayDescription() {
        return $this->getPayName();
    }
    
    public function canPay($userId) {
        foreach ($this->_orders as $order){
            if(!$order->canPay($userId)){
                return FALSE;
            }
        }    
        return TRUE;
    }
    

    public function save() {
        foreach ($this->_orders as $order){
            $order->save();
        }
    }
    /**
     * 获取商品信息
     * @return type
     */
    public function getshipdetail() {
        return Application_Model_OrderItem::getByOrderId($this->_id);
    }
    
    
}